// src/user/user.controller.ts
import { Controller, Post, Body, Get, Param } from '@nestjs/common';
import { UserService } from '../services/User.service';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { CreateUserDto } from '../dto/create-user.dto';
import { WxService } from '@src/modules/wx/wx.service';
import { JwtService } from '@src/modules/auth/jwt.service';


@Controller('user')
@ApiTags('登录')
export class UserController {
  constructor(private userService: UserService,
              private readonly wxService: WxService,
              private readonly jwtService: JwtService,
  ) {
  }

  @Post('register')
  @ApiOperation({ summary: '注册新用户' })
  @ApiResponse({ status: 201, description: '注册成功！' })
  @ApiResponse({ status: 400, description: '用户名被占用或验证失败' })
  async register(@Body() createUserDto: CreateUserDto) {
    await this.userService.register(createUserDto.username, createUserDto.password);
    return { message: '注册成功！' };
  }

  @Post('login')
  @ApiOperation({ summary: '用户登录' })
  @ApiResponse({ status: 200, description: '登录成功！' })
  @ApiResponse({ status: 400, description: '用户名不存在或密码错误' })
  async login(@Body() createUserDto: CreateUserDto) {
    const { token } = await this.userService.login(createUserDto.username, createUserDto.password);
    return { message: '登录成功！', token };
  }

  @Get('login/:code')
  @ApiOperation({ summary: '微信登录' })
  @ApiResponse({ status: 200, description: '登录成功' })
  @ApiResponse({ status: 401, description: '登录失败' })
  async wxLogin(@Param('code') code: string) {
    const { openId } = await this.wxService.code2Session(code);

    let user = await this.userService.findByOpenId(openId);

    if (!user) {
      //创建新用户
      user = await this.userService.create(openId);
    }

    const payload = { id: user.id, openID: user.wxID };
    const token = await this.jwtService.sign(payload);
    return { token };
  }
}
